<template>
  <div :class="{hidden:hidden}" class="pagination-container">
    <el-pagination
      :background="background"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :layout="layout"
      :page-sizes="pageSizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { computed } from 'vue'
import { scrollTo } from '@/utils/scroll-to'
export default {
  name: 'Pagination',
  props: {
    total: {
      required: true,
      type: Number
    },
    page: {
      type: Number,
      default: 1
    },
    limit: {
      type: Number,
      default: 10
    },
    pageSizes: {
      type: Array,
      default() {
        return [10, 20, 50, 100]
      }
    },
    layout: {
      type: String,
      default: 'total, sizes, prev, pager, next, jumper'
    },
    background: {
      type: Boolean,
      default: true
    },
    autoScroll: {
      type: Boolean,
      default: true
    },
    hidden: {
      type: Boolean,
      default: false
    }
  },
  emits: ["update:page", "update:limit", "pagination"],
  setup(props, context) {
    const currentPage = computed({
      get: () => props.page,
      set: val => {
        context.emit('update:page', val)
      }
    })
    const pageSize = computed({
      get: () => props.limit,
      set: val => {
        context.emit('update:limit', val)
      }
    })
    function handleSizeChange(val) {
      context.emit('pagination', { page: currentPage, limit: val })
      if (props.autoScroll) {
        scrollTo(0, 800)
      }
    }
    function handleCurrentChange(val) {
      context.emit('pagination', { page: val, limit: pageSize })
      if (props.autoScroll) {
        scrollTo(0, 800)
      }
    }
    return {
      currentPage,
      pageSize,
      handleSizeChange,
      handleCurrentChange
    }
  },
}
</script>

<style scoped>
.pagination-container {
  background: #fff;
  padding: 32px 16px;
}
.pagination-container.hidden {
  display: none;
}
</style>
